package com.unicom_ng;

import com.facebook.react.ReactActivity;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import android.view.KeyEvent;
import org.devio.rn.splashscreen.SplashScreen;
import android.os.Bundle;

import javax.annotation.Nullable;
import com.unicom_ng.rfid.InfraredModule;
import com.unicom_ng.rfid.RfidModule;

public class MainActivity extends ReactActivity {

  /**
   * Returns the name of the main component registered from JavaScript. This is used to schedule
   * rendering of the component.
   */
  @Override
  protected String getMainComponentName() {
    return "unicom_ng";
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    SplashScreen.show(this);
    super.onCreate(savedInstanceState);
    try{
      if(android.os.Build.MODEL.equals("common")){
        RfidModule.create();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    try{
      if(android.os.Build.MODEL.equals("common")){
        InfraredModule.create();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
  protected void onStop() {
    super.onStop();
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    try{
      RfidModule.release();
    } catch (Exception e) {
      e.printStackTrace();
    }
    try{
      InfraredModule.release();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }



  private void sendEvent(ReactContext reactContext,
                         String eventName,
                         @Nullable WritableMap params) {
        reactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
  }

  @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        ReactContext reactContext = getReactInstanceManager().getCurrentReactContext();
        WritableMap params = Arguments.createMap();
        params.putInt("which", event.getKeyCode());
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            sendEvent(reactContext, "keydown", params);
        } else if (event.getAction() == KeyEvent.ACTION_UP) {
            sendEvent(reactContext, "keyup", params);
        }
        return super.dispatchKeyEvent(event);
    }

}
